///<reference path="../typings/tsd.d.ts" />
interface JQuery {
    submenupicker(): JQuery;
    tabs(a?: any, b?: any): JQuery;
    menu(a?: any, b?: any): JQuery;
}
$(function() {
    //系统顶部及项目显示树都是树形结构
    let menuData = window.MENUDATA;
    let orgData = window.ORGDATA;
    if (!menuData) {
        menuData = [{ ID: "1", PID: "0", NAME: "root", ISLEAF: "0" },
            { ID: "11", PID: 1, NAME: "LEAF1", ISLEAF: "1", URL: "sipcquery.html?node=zhtj" },
            { ID: "2", PID: "0", NAME: "root2", ISLEAF: "0" },
            { ID: "21", PID: 2, NAME: "LEAF21", ISLEAF: "1" },
            { ID: "22", PID: 2, NAME: "LEAF22", ISLEAF: "0" },
            { ID: "23", PID: 2, NAME: "LEAF23", ISLEAF: "1" },
            { ID: "221", PID: 22, NAME: "LEAF221", ISLEAF: "1" },
            { ID: "222", PID: 22, NAME: "LEAF222", ISLEAF: "1" }
        ];
        orgData = menuData;
    }
    //1、获取菜单下所有子菜单
    function getSubMenuinfo(pid) {
        var arr = [];
        $.each(menuData, function(i, menuinfo) {
            if (menuinfo.PID == pid) {
                arr.push(menuinfo);
            }
        });
        return arr;
    }
    /** 2、渲染一个菜单，并递归出它所有子菜单 
     * 如果是叶子节点，则增加data-url,到时再协商这个值如何传。
     */
    function renderMenuItem(menuInfo, level) {
        if (menuInfo.ISLEAF == "1") {
            return `<li><a data-id='${menuInfo.ID}' data-url='${menuInfo.URL}'>${menuInfo.NAME}</a></li>`;
        } else {
            var retStr = '';
            if (level == 0) {
                retStr = '<li class="dropdown">';
                retStr += `<a href="#" data-id="${menuInfo.ID}" data-toggle="dropdown" data-submenu >${menuInfo.NAME} <span class='caret'></span></a>`;
            }
            else {
                retStr = '<li class="dropdown-submenu">';
                retStr += `<a href="#" data-id="${menuInfo.ID}"> ${menuInfo.NAME} </a>`;
            }
            retStr += '<ul class="dropdown-menu">';
            //循环所有子菜单，并渲染子菜单
            $.each(getSubMenuinfo(menuInfo.ID), function(i, info) {
                retStr += renderMenuItem(info, level + 1);
            });
            //补上闭合标签
            retStr += '</ul></li>';
            return retStr;
        }
    }
    //3、渲染一级菜单
    function renderMenu() {
        var retStr = "";
        $.each(getSubMenuinfo("0"), function(i, info) {
            retStr += renderMenuItem(info, 0);
        });
        $("#ulMenu").append(retStr);
        $('[data-submenu]').submenupicker();
    }
    renderMenu();
    //4、顶部菜单点击时，要打开新标签
    $("#ulMenu").on("click", "[data-url]", function() {
        let $a = $(this);
        window.addFrameTab($a.text(), $a.data("url"));
    });


    //加载项目树
    window.CurTreeNode = orgData[0];
    var setting = {
        data: {
            key: {
                name: "NAME",
                title: "NAME"//提示信息的属性名称
            },
            simpleData: {
                enable: true,
                idKey: "ID",
                pIdKey: "PID"
            }
        },
        callback: {
            //点击节点后，向当前或所有标签窗口发送消息。通知ZZJGID变化
            onClick: function(event, treeId, treeNode: TreeNode) {
                //全局保存当前节点
                window.CurTreeNode = treeNode;
                //这是向所有标签发出通知
                $("iframe").each(function(i, frm: HTMLIFrameElement) {
                    frm.contentWindow.postMessage(JSON.stringify(treeNode), "*");
                });
            }
        }
    };
    var treeObj = $.fn.zTree.init($("#ulOrgTree"), setting, orgData);
    var nodes = treeObj.getNodes();
    treeObj.expandNode(nodes[0], true, false, true);

    /**设置标签功能 */
    $('#topTabs').tabs({
        fit: true,
        border: false
    });
    //添加标签  allowfullscreen
    window.addFrameTab = function(title, url) {
        if ($('#topTabs').tabs('exists', title)) {
            //已经存在，则更新一下url
            let tab = $('#topTabs').tabs('getTab', title);
            tab.find("iframe").attr("src", url);
            $('#topTabs').tabs('select', title);
        } else {
            var _content = $('<iframe  scrolling="auto" ></iframe>');
            $('#topTabs').tabs('add', { title: title, content: _content[0], url: url, closable: true, closed: true, fit: true });
            _content.attr('id', 'tab_' + title).attr('title', title).attr('src', url).attr('frameborder', '0').css({ width: "100%", height: "100%" })
        }
    }
    window.addFrameTab("首页", "sipcquery.html?node=zhtj");

    //右键,双击
    $('#topTabs').on('contextmenu', '.tabs-inner', function(e) {
        $('#mm').menu('show', { left: e.pageX, top: e.pageY });
        $('#mm').data("currtab", $(this).children("span").text());
        return false;
    }).on('dblclick', '.tabs-inner', function() {
        $('#topTabs').tabs('close', $(this).children(".tabs-title").text());
    });
    //关闭当前
    $('#mm-tabclose').click(function() {
        $('#topTabs').tabs('close', $('#mm').data("currtab"));
    });
    //全部关闭
    $('#mm-tabcloseall').click(function() {
        $('.tabs-inner span').each(function(i, n) {
            if ($(n).hasClass('tabs-closable') == false) return;
            $('#topTabs').tabs('close', $(n).text());
        });
    });
    //关闭其它
    $('#mm-tabcloseother').click(function() {
        $('.tabs-inner span').each(function(i, n) {
            if ($(n).hasClass('tabs-closable') == false) return;
            if ($(n).text() == $('#mm').data("currtab")) return;
            $('#topTabs').tabs('close', $(n).text());
        });
    });
    //关闭右侧
    $('#mm-tabcloseright').click(function() {
        var count = 0, nextall = $('.tabs-selected').nextAll();
        nextall.each(function(i, n) {
            if ($('.tabs-title', $(n)).hasClass('tabs-closable') == false) return;
            $('#topTabs').tabs('close', $('a:eq(0) span', $(n)).text()); count = count + 1;
        });
        return false;
    });
    //关闭左侧
    $('#mm-tabcloseleft').click(function() {
        var count = 0, prevall = $('.tabs-selected').prevAll();
        prevall.each(function(i, n) {
            if ($('.tabs-title', $(n)).hasClass('tabs-closable') == false) return;
            $('#topTabs').tabs('close', $('a:eq(0) span', $(n)).text()); count = count + 1;
        });
        return false;
    });



});